﻿using System.Collections;
using UnityEngine;

public class Bomb : MonoBehaviour
{
    public float bombRadius = 20f;
    public float bombForce = 100f;
    public float fuseTime = 1f;
    public ParticleSystem explosionFX;
    public GameObject explosionCircle;
    public AudioClip bigBoom;

    // Start is called before the first frame update
    void Start()
    {
        explosionFX = GameObject.Find("explosionParticle").GetComponent<ParticleSystem>();
        if (transform.root == transform)
            StartCoroutine(Detonation());
    }

    public void onExplode()
    {
        
        GameObject.Find("BombAS").GetComponent<AudioSource>().PlayOneShot(bigBoom);

        explosionFX.transform.position = transform.position;
        explosionFX.Play();
        Destroy(transform.root.gameObject);
        Instantiate(explosionCircle, transform.position, Quaternion.identity);
        Collider2D[] cols = Physics2D.OverlapCircleAll(transform.position, bombRadius);
        foreach(Collider2D col in cols)
        {
            Rigidbody2D rb = col.GetComponent<Rigidbody2D>();
            if(rb != null && rb.tag == "Enemy")
            {
                
                if(col.GetComponent<Enemy>().hp > 0)
                    col.GetComponent<Enemy>().hurt(2);

                rb.AddForce((col.transform.position - transform.position).normalized * bombForce);
            }
            else if(col.tag == "Bomb")
            {
                Debug.Log(col.tag);
                col.GetComponent<Bomb>().onExplode();
            }
            else if(col.tag == "Other")
            {
                col.GetComponent<HealthPickup>().Drop();
            }
        }
    }
    IEnumerator Detonation()
    {
        yield return new WaitForSeconds(fuseTime);
        onExplode();
    }
}
